const env = require('../config.js').ENV; //配置文件，在这里配置你的OSS keyId和KeySecret,timeout:87600;
//更好的做法是把这些信息放到服务器进行签名，防止信息泄露

const Base64 = require('./Base64.js');//Base64,hmac,sha1,crypto相关算法
//参考这里https://github.com/peterhuang007/weixinFileToaliyun.git

require('./crypto/hmac.js');
require('./crypto/sha1.js');
const Crypto = require('./crypto/crypto.js');

const uploadFile = function (params) {
  // if (!params.filePath || params.filePath.length < 9) {
  //   wx.showModal({
  //     title: '图片错误',
  //     content: '请重试',
  //     showCancel: false,
  //   })
  //   return;
  // }
  console.log('filePath=', params.filePath);
  let filePath = params.filePath;
  const aliyunFileKey = params.dir + filePath.replace('wxfile://', '');

  const aliyunServerURL = env.uploadVoiceUrl;
  const accessid = env.OSSAccessKeyId;
  const policyBase64 = getPolicyBase64();
  const signature = getSignature(policyBase64);

  console.log('aliyunFileKey=', aliyunFileKey);
  console.log('aliyunServerURL=', aliyunServerURL);
  wx.uploadFile({
    url: aliyunServerURL,
    filePath: filePath,
    name: 'file',
    formData: {
      'key': aliyunFileKey,
      'policy': policyBase64,
      'OSSAccessKeyId': accessid,
      'signature': signature,
      'success_action_status': '200',
    },
    success: function (res) {
      if (res.statusCode != 200) {
        if (params.fail) {
          params.fail(res)
        }
        return;
      }
      if (params.success) {
        params.success({ key: aliyunFileKey, formId: params.formId});
      }
    },
    fail: function (err) {
      console.log("fail==")
      err.wxaddinfo = aliyunServerURL;
      if (params.fail) {
        params.fail(err)
      }
    },
  })
}

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间
    "conditions": [
      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = env.OSSAccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
}

module.exports = uploadFile;
